from flask import request, g
from models import store
from models.user import User
from extensions import db
from utils.auth import token_required
from flask_restx import Namespace, Resource, fields
from models.card_package import CardPackage
from datetime import datetime, timedelta
import uuid
from models.user_store import UserStore
from models.store import Store
from models.card_consumption import CardConsumption
from sqlalchemy import func

api = Namespace('users', description='用户管理相关接口')

# 定义API模型
user_model = api.model('User', {
    'staff_id': fields.String(description='销售员ID'),
    'user_id': fields.String(required=True, description='用户ID'),
    'name': fields.String(required=True, description='用户姓名'),
    'phone': fields.String(required=True, description='手机号'),
    'roles': fields.String(required=True, description='用户角色（admin,customer）'),
    'password': fields.String(required=True, description='密码'),
    'store_id': fields.String(description='所属店铺ID'),
    'manager_hierarchy_id': fields.String(description='管理层级ID'),
    'gender': fields.String(enum=['male', 'female'], description='性别'),
    'birthday': fields.DateTime(description='生日'),
    'remarks': fields.String(description='备注'),
    'created_at': fields.DateTime(description='创建时间'),
    'updated_at': fields.DateTime(description='更新时间'),
    'is_deleted': fields.Boolean(description='是否删除'),
    'user_store': fields.Nested(api.model('UserStore', {
        'id': fields.Integer(description='用户店铺关系ID'),
        'user_id': fields.String(description='用户ID'),
        'store_id': fields.String(description='店铺ID'),
        'role': fields.String(description='用户在店铺中的角色'),
        'discount_rate': fields.Float(description='用户折扣比例'),
        'commission_rate': fields.Float(description='用户提成比例'),
        'equity_ratio': fields.Float(description='用户占股份额'),
        'created_at': fields.DateTime(description='创建时间'),
        'updated_at': fields.DateTime(description='更新时间'),
        'is_deleted': fields.Boolean(description='是否删除')
    }), required=False, description='用户店铺关系信息')
})

login_model = api.model('Login', {
    'phone': fields.String(required=True, description='手机号'),
    'password': fields.String(required=True, description='密码')
})

base_response = api.model('BaseResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息')
})

user_response = api.inherit('UserResponse', base_response, {
    'data': fields.Nested(user_model)
})

user_list_response = api.inherit('UserListResponse', base_response, {
    'data': fields.List(fields.Nested(user_model))
})

login_response = api.inherit('LoginResponse', base_response, {
    'data': fields.Nested(api.model('LoginData', {
        'token': fields.String(description='JWT令牌'),
        'user_info': fields.Nested(user_model)
    }))
})

card_package_response = api.model('CardPackageResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息'),
    'data': fields.Raw(description='响应数据', required=False)
})

@api.route('/')
class UserList(Resource):
    @api.doc('获取所有用户列表')
    @api.marshal_with(user_list_response)
    @token_required
    def get(self):
        users = User.query.filter_by(is_deleted=False).order_by(db.desc(User.id)).all()
        return {
            'status': 'success',
            'data': [user.to_dict() for user in users]
        }, 200

@api.route('/<store_id>/<user_id>')
class StoreUserResource(Resource):
    @api.doc('获取单个用户信息')
    @api.marshal_with(user_response)
    @token_required
    def get(self, store_id, user_id):
        """获取单个用户信息及其管理的店铺"""  
        # 获取用户信息及关联的UserStore信息
        query = db.session.query(
            User,
            UserStore
        ).outerjoin(
            UserStore,
            db.and_(
                UserStore.user_id == user_id,
                UserStore.store_id == store_id,
                UserStore.is_deleted == False
            )
        ).filter(
            User.user_id == str(user_id),
            User.is_deleted == False
        )
        
        result = query.first()
        if not result:
            return {
                'status': 'error',
                'message': '用户不存在'
            }, 404
            
        user, user_store = result
        user_data = user.to_dict()
        
        # 添加UserStore信息
        if user_store:
            user_data['user_store'] = user_store.to_dict()
        return {
            'status': 'success',
            'data': user_data
        }, 200

@api.route('/<user_id>')
class UserResource(Resource):
    @api.doc('获取单个用户信息')
    @api.marshal_with(user_response)
    @token_required
    def get(self, user_id):
        """获取单个用户信息及其管理的店铺"""
        from models.store import Store
        
        # 获取用户信息
        user = User.query.filter_by(user_id=str(user_id), is_deleted=False).first_or_404()
        user_data = user.to_dict()
        
        # 获取用户关联的店铺信息
        stores = []
        if user.store_id:  # 如果用户属于某个店铺
            store = Store.query.filter_by(store_id=user.store_id, is_deleted=False).first()
            if store:
                stores.append(store.to_dict())
        
        # 获取该用户作为店长的所有店铺
        managed_stores = Store.query.filter_by(manager_id=user_id, is_deleted=False).all()
        for store in managed_stores:
            if store.to_dict() not in stores:  # 避免重复添加
                stores.append(store.to_dict())
        
        user_data['stores'] = stores
        
        return {
            'status': 'success',
            'data': user_data
        }, 200

    @api.doc('更新用户信息')
    @api.expect(user_model)
    @api.marshal_with(user_response)
    @token_required
    def put(self, user_id):
        """更新用户信息"""
        user = User.query.filter_by(user_id=str(user_id), is_deleted=False).first_or_404()
        data = request.get_json()
        
        # 保存store_id，防止后续被移除
        original_store_id = data.get('store_id')
        
        # 检查是否为平台股东用户
        is_platform_shareholder = False
        if 'store_id' in data and data['store_id']:
            # 检查特定店铺中的角色
            user_store = UserStore.query.filter_by(
                user_id=user_id,
                store_id=data['store_id'],
                is_deleted=False
            ).first()
            if user_store and user_store.role == 'platform_shareholder':
                is_platform_shareholder = True
        else:
            # 检查任何店铺中是否为平台股东
            user_store = UserStore.query.filter_by(
                user_id=user_id,
                role='platform_shareholder',
                is_deleted=False
            ).first()
            if user_store:
                is_platform_shareholder = True
                # 如果是平台股东但没有提供store_id，使用查找到的store_id
                if not original_store_id and user_store:
                    original_store_id = user_store.store_id
        
        # 如果是平台股东，限制可以修改的字段
        if is_platform_shareholder:
            # 平台股东只允许修改特定字段，例如备注
            allowed_fields = ['commission_rate','equity_ratio']
            for field in list(data.keys()):
                if field not in allowed_fields:
                    data.pop(field, None)
            
            # 如果没有任何允许修改的字段，则返回错误
            if not any(field in data for field in allowed_fields):
                return {
                    'status': 'error',
                    'message': '平台股东信息不允许修改，仅支持提成比例和占股股份'
                }, 403
        
        # 更新用户信息
        if 'name' in data:
            user.name = data['name']
        if 'phone' in data:
            # 验证手机号格式
            import re
            if not re.match(r'^1[3-9]\d{9}$', data['phone']):
                return {
                    'status': 'error',
                    'message': '手机号格式不正确'
                }, 400
            # 检查手机号是否已被其他用户使用
            existing_user = User.query.filter_by(phone=data['phone']).first()
            if existing_user and existing_user.user_id != user_id:
                return {
                    'status': 'error',
                    'message': '该手机号已被其他用户使用'
                }, 400
            user.phone = data['phone']
        if 'roles' in data and not is_platform_shareholder:
            # 验证角色格式
            roles = data['roles'].split(',')
            valid_roles = {'owner', 'manager', 'staff', 'customer'}
            if not all(role in valid_roles for role in roles):
                return {
                    'status': 'error',
                    'message': '角色无效，有效角色为: ' + ', '.join(valid_roles)
                }, 400
                
            # 如果角色包含customer，验证staff_id字段
            if 'customer' in roles and 'staff_id' not in data:
                return {
                    'status': 'error',
                    'message': '创建客户时必须指定销售员ID(staff_id)'
                }, 400
            user.roles = data['roles']
        if 'password' in data and not is_platform_shareholder:
            user.password = data['password']
        if 'store_id' in data and not is_platform_shareholder:
            user.store_id = data['store_id']
        if 'manager_hierarchy_id' in data and not is_platform_shareholder:
            user.manager_hierarchy_id = data['manager_hierarchy_id']
        if 'gender' in data and not is_platform_shareholder:
            user.gender = data['gender']
        if 'birthday' in data and not is_platform_shareholder:
            user.birthday = data['birthday']
        if 'remarks' in data:
            user.remarks = data['remarks']
        
        # 更新UserStore信息
        if original_store_id :
            user_store = UserStore.query.filter_by(
                user_id=user_id,
                store_id=original_store_id
            ).first()
            
            if user_store:
                if 'roles' in data:
                    user_store.role = data['roles']
                if 'commission_rate' in data:
                    user_store.commission_rate = float(data['commission_rate'])
                if 'equity_ratio' in data:
                    new_equity_ratio = float(data['equity_ratio'])
                    
                    # 计算店铺中其他用户的股份总和
                    total_equity = round(db.session.query(func.sum(UserStore.equity_ratio)).filter(
                        UserStore.store_id == original_store_id,
                        UserStore.user_id != user_id,
                        UserStore.is_deleted == False
                    ).scalar() or 0,2)
                    
                    # 检查总股份是否超过100%
                    if total_equity + new_equity_ratio > 1.0:
                        return {
                            'status': 'error',
                            'message': f'股份分配超过100%！当前店铺其他用户已占股{total_equity*100:.2f}%，您设置的{new_equity_ratio*100:.2f}%导致总占股为{(total_equity+new_equity_ratio)*100:.2f}%'
                        }, 400
                    
                    user_store.equity_ratio = new_equity_ratio
                db.session.add(user_store)
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '用户信息更新成功',
            'data': user.to_dict()
        }, 200

    @api.doc('删除用户')
    @api.marshal_with(base_response)
    @token_required
    def delete(self, user_id):
        """删除用户（软删除）"""
        user = User.query.filter_by(user_id=user_id).first_or_404()
        
        # 检查是否为平台股东用户，如果是则禁止删除
        user_store = UserStore.query.filter_by(user_id=user_id, is_deleted=False).first()
        if user_store and user_store.role == 'platform_shareholder':
            return {
                'status': 'error',
                'message': '平台股东用户不允许删除'
            }, 403
        
        # 如果用户已经被删除，直接返回成功
        if user.is_deleted:
            return {
                'status': 'success',
                'message': '用户已被删除'
            }, 200
        
        user.is_deleted = True
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '用户删除成功'
        }, 200
@api.route('', strict_slashes=False)
class UserCreate(Resource):
    @api.doc('创建新用户')
    @api.expect(user_model)
    @api.marshal_with(user_response)
    @token_required
    def post(self):
        """创建新用户"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['name', 'phone', 'roles', 'password']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        # 验证手机号格式
        import re
        if not re.match(r'^1[3-9]\d{9}$', data['phone']):
            return {
                'status': 'error',
                'message': '手机号格式不正确'
            }, 400
        
        # 检查手机号是否已存在
        if User.query.filter_by(phone=data['phone'], is_deleted=False).first():
            return {
                'status': 'error',
                'message': '该手机号已被注册'
            }, 400
        
        # 验证角色格式
        roles = data['roles'].split(',')
        valid_roles = {'owner', 'manager', 'staff', 'customer'}
        if not all(role in valid_roles for role in roles):
            return {
                'status': 'error',
                'message': '角色无效，有效角色为: ' + ', '.join(valid_roles)
            }, 400
             # 如果角色包含customer，验证staff_id字段
        if 'customer' in roles and 'staff_id' not in data:
            return {
                'status': 'error',
                'message': '创建客户时必须指定销售员ID(staff_id)'
            }, 400
        
        # 移除店铺关联验证，因为现在只有admin和customer角色
       
        # 创建新用户
        new_user = User(
            user_id=str(uuid.uuid4()),
            name=data['name'],
            phone=data['phone'],
            roles=data['roles'],
            store_id=data.get('store_id'),
            manager_hierarchy_id=data.get('manager_hierarchy_id'),
            gender=data.get('gender'),
            birthday=data.get('birthday'),
            remarks=data.get('remarks'),
            staff_id=data.get('staff_id'),
        )
        new_user.password = data['password']
        # 将新用户添加到数据库会话
        db.session.add(new_user)
        # 如果当前有登录店铺，创建用户店铺关系

        if 'store_id' in data and data['store_id']:
             # 检查股份比例是否合法
            if 'equity_ratio' in data and float(data.get('equity_ratio', 0)) > 0:
                new_equity_ratio = float(data['equity_ratio'])
                
                # 计算店铺中其他用户的股份总和
                total_equity = round(db.session.query(func.sum(UserStore.equity_ratio)).filter(
                    UserStore.store_id == data['store_id'],
                    UserStore.is_deleted == False
                ).scalar() or 0,2)
                
                # 检查总股份是否超过100%
                if total_equity + new_equity_ratio > 1.0:
                    return {
                        'status': 'error',
                        'message': f'股份分配超过100%！当前店铺其他用户已占股{total_equity*100:.2f}%，您设置的{new_equity_ratio*100:.2f}%导致总占股为{(total_equity+new_equity_ratio)*100:.2f}%'
                    }, 400
            
            user_store = UserStore(
                user_id=new_user.user_id,
                store_id=data['store_id'],
                role=data['roles'],  # 默认角色为员工
                commission_rate=float(data.get('commission_rate', 0)),  # 添加提成比例
                equity_ratio=float(data.get('equity_ratio', 0))  # 添加占股份额
            )
            db.session.add(user_store)

            if 'customer' in data['roles'].split(',') and ('store_id' in data and data['store_id']):
                 #通过store_id差选店铺
                store = Store.query.filter_by(store_id=data['store_id'], is_deleted=False).first()
                if not store:
                    return {
                        'status': 'error',
                        'message': '店铺不存在'  
                    }
                # 查询店铺下的所有默认卡包
                default_package_list = CardPackage.query.filter_by(
                card_type='default',# 系统默认卡包
                store_id=user_store.store_id,
                user_id=None ,
                is_deleted=False
                ).all()
                for package in default_package_list:
                    new_card_package = CardPackage(
                        package_id=str(uuid.uuid4()),
                        name=package.name,
                        card_type=package.card_type,
                        store_id=store.store_id,  # 关联到新店铺
                        user_id=new_user.user_id,  # 关联到新用户
                        parent_card_package_id=package.package_id,  # 设置父卡包ID
                        total_amount=package.total_amount,
                        remaining_amount=package.remaining_amount,
                        discount_rate=package.discount_rate,
                        commission_rate=package.commission_rate,
                        expiry_date=package.expiry_date,
                        recharge_amount=package.recharge_amount,
                        gift_amount=package.gift_amount,
                        commission_amount=package.commission_amount,
                        is_deleted=False
                    )

                    db.session.add(new_card_package)
                    # if package.recharge_amount and package.recharge_amount > 0:
                    #     #记录交易详情
                    #     transactions = []
                    #     curent_user = g.current_identity
                        
                    #     # 现金支付记录 (交易类型1-卡包充值)
                    #     transactions.append((1, 1, package.recharge_amount, curent_user.user_id,None))
                        
                    #     # 提成记录 (交易类型5-提成支出)
                    #     commission = round(package.recharge_amount * package.commission_rate, 2)
                    #     transactions.append((5, 0, commission, curent_user.user_id,None))
                        
                    #     # 计算剩余余额（收入减去支出）
                    #     total_income = package.recharge_amount
                    #     total_expense = commission
                    #     remaining_balance = round(total_income - total_expense, 2)
                        
                    #     # 无论余额是正是负，都需要按照股东比例分配或分摊
                    #     # 查询店铺中有股份的用户（排除平台股东）
                    #     store_shareholders = db.session.query(UserStore, User.id).join(
                    #         User, UserStore.user_id == User.user_id
                    #     ).filter(
                    #         UserStore.store_id == data['store_id'],
                    #         UserStore.equity_ratio > 0,
                    #         UserStore.role != 'platform_shareholder',
                    #         User.is_deleted == False
                    #     ).all()
                        
                    #     # 分配给普通股东的总金额
                    #     distributed_amount = 0
                        
                    #     # 为每个股东生成分配记录
                    #     for shareholder,user_id in store_shareholders:
                    #         if shareholder.equity_ratio > 0:
                    #             # 直接使用数据库中的股份比例计算
                    #             shareholder_amount = round(remaining_balance * shareholder.equity_ratio, 2)
                                
                    #             # 无论金额是正是负都记录
                    #             amount = abs(shareholder_amount)
                    #             income_type = 0 if remaining_balance > 0 else 1  # 如果是负数，记为收入（分摊成本）
                                
                    #             # 创建记录（店铺支出）
                    #             transactions.append((9, income_type, amount,user_id,shareholder.equity_ratio,))
                    #             distributed_amount += shareholder_amount
                        
                    #     # 计算分配后剩余的金额
                    #     platform_remaining = round(remaining_balance - distributed_amount, 2)
                        
                    #     # 无论是盈利还是亏损，剩余部分都分配给平台股东
                    #     if abs(platform_remaining) > 0:
                    #         # 查询平台股东
                    #         platform_shareholders = db.session.query(UserStore, User.id).join(
                    #             User, UserStore.user_id == User.user_id
                    #         ).filter(
                    #             UserStore.store_id == data['store_id'],
                    #             UserStore.role == 'platform_shareholder',
                    #             User.is_deleted == False
                    #         ).all()
                            
                    #         if platform_shareholders:
                    #             # 如果有多个平台股东，按照他们的股份比例分配
                    #             platform_total_equity = sum(ps.equity_ratio for ps in platform_shareholders)
                                
                    #             for platform_shareholder,user_id in platform_shareholders:
                    #                 if platform_total_equity > 0:
                    #                     # 按比例分配平台股东的份额
                    #                     platform_share = round(platform_remaining * (platform_shareholder.equity_ratio / platform_total_equity), 2)
                    #                 else:
                    #                     # 如果没有设置股份比例，平均分配
                    #                     platform_share = round(platform_remaining / len(platform_shareholders), 2)
                                    
                    #                 # 确定收支类型
                    #                 # 如果是负数，记为收入（分摊成本）
                    #                 amount = platform_share # 取绝对值记录
                    #                 # 创建平台股东分配记录
                    #                 transactions.append((10, 0, amount,user_id,platform_shareholder.equity_ratio))
                    #         for transaction_type, income_type, amount_used, staff_id,equity_ratio  in transactions:
                    #             consumption = CardConsumption(
                    #                 transaction_type=transaction_type,
                    #                 income_type=income_type,
                    #                 amount_used=amount_used,
                    #                 staff_id=staff_id,
                    #                 equity_ratio=equity_ratio,
                    #                 store_id=store.id,
                    #                 card_package_id=package.id,
                    #                 user_id=new_user.id,
                    #                 product_id=None,
                    #                 consumption_date=datetime.now(),
                    #                 order_id=None,
                    #                 card_type=package.card_type
                    #             )
                    #             db.session.add(consumption)
            
        db.session.commit()

        
        return {
            'status': 'success',
            'message': '用户创建成功',
            'data': new_user.to_dict()
        }, 200
@api.route('/register', strict_slashes=False)
class UserRegister(Resource):
    @api.doc('注册新用户')
    @api.expect(user_model)
    @api.marshal_with(user_response)
    def post(self):
        """创建新用户"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['name', 'phone', 'roles', 'password']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        # 验证手机号格式
        import re
        if not re.match(r'^1[3-9]\d{9}$', data['phone']):
            return {
                'status': 'error',
                'message': '手机号格式不正确'
            }, 400
        
        # 检查手机号是否已存在
        if User.query.filter_by(phone=data['phone'], is_deleted=False).first():
            return {
                'status': 'error',
                'message': '该手机号已被注册'
            }, 400
        
        # 验证角色格式
        roles = data['roles'].split(',')
        valid_roles = {'owner', 'manager', 'staff', 'customer'}
        if not all(role in valid_roles for role in roles):
            return {
                'status': 'error',
                'message': '角色无效，有效角色为: ' + ', '.join(valid_roles)
            }, 400
        
        # 移除店铺关联验证，因为现在只有admin和customer角色
       
        # 创建新用户
        new_user = User(
            user_id=str(uuid.uuid4()),
            name=data['name'],
            phone=data['phone'],
            roles=data['roles'],
            store_id=data.get('store_id'),
            manager_hierarchy_id=data.get('manager_hierarchy_id'),
            gender=data.get('gender'),
            birthday=data.get('birthday'),
            remarks=data.get('remarks')
        )
        new_user.password = data['password']
        # 将新用户添加到数据库会话
        db.session.add(new_user)
        # 如果当前有登录店铺，创建用户店铺关系
            
        db.session.commit()

        
        return {
            'status': 'success',
            'message': '用户创建成功',
            'data': new_user.to_dict()
        }, 200

@api.route('/login')
class UserLogin(Resource):
    @api.doc('用户登录')
    @api.expect(login_model)
    @api.marshal_with(login_response)
    def post(self):
        """用户登录"""
        from utils.auth import generate_token
        
        data = request.get_json()
        
        # 检查必填字段
        if 'phone' not in data or 'password' not in data:
            return {
                'status': 'error',
                'message': '请提供手机号和密码'
            }, 401
        
        # 检查密码是否为空
        if data.get('password', '') == '':
            return {
                'status': 'error',
                'message': '密码不能为空'
            }, 401
            
        # 验证手机号格式
        import re
        if not re.match(r'^1[3-9]\d{9}$', data['phone']):
            return {
                'status': 'error',
                'message': '手机号格式不正确'
            }, 401
        
        # 查找用户
        user = User.query.filter_by(phone=data['phone']).first()
        
        # 检查用户是否存在
        if not user:
            return {
                'status': 'error',
                'message': '用户不存在'
            }, 401
        
        # 检查用户是否已被删除
        if user.is_deleted:
            return {
                'status': 'error',
                'message': '用户不存在或已被删除'
            }, 401
        
        # 验证密码
        if not user.check_password(data['password']):
            return {
                'status': 'error',
                'message': '手机号或密码错误',
                'data': None
            }, 401
        
        # 生成令牌
        token = generate_token(user)
        
        return {
            'status': 'success',
            'message': '登录成功',
            'data': {
                'token': token,
                'user_info': user.to_dict()
            }
        }, 200

@api.route('/logout')
class UserLogout(Resource):
    @api.doc('用户登出')
    @api.marshal_with(base_response)
    @token_required
    def post(self):
        """用户登出，吊销当前令牌"""
        from utils.auth import decode_token, revoke_token
        auth_header = request.headers.get('Auuua') or request.headers.get('AUUUA')
        if not auth_header:
            return {
                'status': 'error',
                'message': '缺少有效的认证令牌'
            }, 400
        
        try:
            # 解码令牌并获取必要信息
            data = decode_token(auth_header)
            # 将令牌加入黑名单
            revoke_token(data['jti'], data['exp'])
            
            return {
                'status': 'success',
                'message': '登出成功'
            }, 200
        except Exception as e:
            return {
                'status': 'error',
                'message': f'登出失败：{str(e)}'
            }, 400

@api.route('/valid')
class UserValid(Resource):
    @api.doc('验证token有效性')
    @api.marshal_with(base_response)
    @token_required
    def get(self):
        """验证token有效性，用于前端页面打开时的验证"""
        return {
            'status': 'success',
            'message': '令牌有效'
        }, 200

@api.route('/<user_id>/bind_card_package/<store_id>/<package_id>')
class BindCardPackage(Resource):
    @api.doc('绑定卡包到用户')
    @api.marshal_with(base_response)
    @token_required
    def post(self, user_id, store_id, package_id):
        """绑定卡包到用户"""
        from models.store import Store
        from models.card_package import CardPackage
        data = request.get_json()
        
        # 校验必填参数
        required_fields = ['staff_id']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        # 检查用户是否存在
        user = User.query.filter_by(user_id=user_id, is_deleted=False).first_or_404()
        staff_user=User.query.filter_by(user_id=data['staff_id'],is_deleted=False).first_or_404()
        # 检查店铺是否存在
        store = Store.query.filter_by(store_id=store_id, is_deleted=False).first_or_404()
        
        # 检查卡包是否存在
        original_package = CardPackage.query.filter_by(
            package_id=package_id, 
            store_id=store_id,
            is_deleted=False
        ).first_or_404()
        
        # 创建新的卡包副本
        new_package = CardPackage(
            package_id=str(uuid.uuid4()),
            name=original_package.name,
            card_type=original_package.card_type,
            total_amount=original_package.total_amount,
            remaining_amount=original_package.total_amount,  # 初始剩余量等于总量
            commission_rate=original_package.commission_rate,
            discount_rate=original_package.discount_rate,
            recharge_amount=original_package.recharge_amount,
            gift_amount=original_package.gift_amount,
            expiry_date=original_package.expiry_date,
            user_id=user_id,  # 绑定到用户
            store_id=store_id,
            parent_card_package_id=package_id  # 关联到原始卡包
        )

         # 记录交易详情
        db.session.add(new_package)
        transactions = []
        curent_user = g.current_identity
        # 现金支付记录 (交易类型1-卡包充值)
        transactions.append((1, 1, original_package.recharge_amount,staff_user.id,None))
        # 提成记录 (交易类型5-提成支出)
        commission = round(original_package.recharge_amount * original_package.commission_rate, 2)
        
        transactions.append((5, 0, commission,staff_user.id,None))
        #股东分红记录 (交易类型9-股东分红)
        # 计算剩余余额（收入减去支出）
        total_income = original_package.recharge_amount
        total_expense = commission
        remaining_balance = round(total_income - total_expense, 2)
        
        # 无论余额是正是负，都需要按照股东比例分配或分摊
        # 查询店铺中有股份的用户（排除平台股东）
        store_shareholders = db.session.query(UserStore, User.id).join(
            User, UserStore.user_id == User.user_id
        ).filter(
            UserStore.store_id == store_id,
            UserStore.equity_ratio > 0,
            UserStore.role != 'platform_shareholder',
            User.is_deleted == False
        ).all()
        
        # 分配给普通股东的总金额
        distributed_amount = 0
        
        # 为每个股东生成分配记录
        for shareholder, staff_id in store_shareholders:
            if shareholder.equity_ratio > 0:
                # 直接使用数据库中的股份比例计算
                shareholder_amount = round(remaining_balance * shareholder.equity_ratio, 2)
                
                # 无论金额是正是负都记录
                amount = shareholder_amount              
            
                # 创建记录（店铺支出）
                transactions.append((9, 0, amount, staff_id, shareholder.equity_ratio))
                distributed_amount += shareholder_amount
        
        # 计算分配后剩余的金额
        platform_remaining = round(remaining_balance - distributed_amount, 2)
        
        # 无论是盈利还是亏损，剩余部分都分配给平台股东
        # 查询平台股东
        platform_shareholders = db.session.query(UserStore, User.id).join(
            User, UserStore.user_id == User.user_id
        ).filter(
            UserStore.store_id == store_id,
            UserStore.role == 'platform_shareholder',
            User.is_deleted == False
        ).all()
        
        if platform_shareholders and platform_remaining != 0:
            # 如果有多个平台股东，按照他们的股份比例分配
            platform_total_equity = sum(ps[0].equity_ratio for ps in platform_shareholders)
            for platform_shareholder, staff_id in platform_shareholders:
                if platform_total_equity > 0:
                    # 按比例分配平台股东的份额
                    platform_share = round(platform_remaining * (platform_shareholder.equity_ratio / platform_total_equity), 2)
                else:
                    # 如果没有设置股份比例，平均分配
                    platform_share = round(platform_remaining / len(platform_shareholders), 2)
                
                # 确定收支类型
                amount = platform_share
                # 创建平台股东分配记录
                transactions.append((10, 0, amount, staff_id, platform_shareholder.equity_ratio))
        
            
        for transaction_type, income_type, amount_used,staff_id,equity_ratio in transactions:
            consumption = CardConsumption(
                transaction_type=transaction_type,
                income_type=income_type,
                amount_used=amount_used,
                staff_id=staff_id,
                equity_ratio=equity_ratio,
                handle_user_id=curent_user.id,
                store_id=store.id,
                card_package_id=original_package.id,
                user_id=user.id,
                product_id=None,
                consumption_date=datetime.now(),
                order_id=None,
                card_type=original_package.card_type
            )
            db.session.add(consumption)

        db.session.commit()
        
        return {
            'status': 'success',
            'message': '卡包绑定成功',
            'data': new_package.to_dict()
        }, 201

@api.route('/card_package_list/<user_id>', strict_slashes=False)
class CardPackageList(Resource):
    @api.doc('获取卡包列表', params={
        'store_id': '店铺ID（可选）',
        'billing_type': '计费类型（可选）',
        'name': '卡包名称（可选，模糊查询）'
    })
    @api.marshal_with(card_package_response)
    @token_required
    def get(self,user_id):
        """获取卡包列表"""
        
        if not user_id:
            return {
                'status': 'error',
                'message': '必须提供用户ID'
            }, 400
        store_id = request.args.get('store_id')
        if not store_id:
            return {
                'status': 'error', 
                'message': '必须提供店铺ID'
            }, 400
        # 基础查询条件
        query = CardPackage.query.filter_by(is_deleted=False)
        
        # 构建查询条件
        query = query.filter(
                    CardPackage.store_id == store_id,
                    CardPackage.user_id.is_(None)
                )
        
        # 其他过滤条件
        card_type = request.args.get('card_type')
        if card_type:
            query = query.filter(CardPackage.card_type == card_type)
            
        name = request.args.get('name')
        if name:
            query = query.filter(CardPackage.name.like(f'%{name}%'))
        
        # 按创建时间倒序排序
        card_packages = query.order_by(CardPackage.created_at.desc()).all()
        
        query_user = CardPackage.query.filter_by(is_deleted=False)
        # 构建查询条件
        query_user = query_user.filter(
            CardPackage.store_id == store_id,
            CardPackage.user_id == user_id
        )
        # 按创建时间倒序排序
        user_card_packages = query_user.order_by(CardPackage.created_at.desc()).all()
        # 以card_packages为主循环，当它的package_id在user_card_packages中存在时，将其is_owned属性设置为True
        user_package_map = {
            p.parent_card_package_id: p 
            for p in user_card_packages
        }
        
        for package in card_packages:
            package.is_owned = package.package_id in user_package_map
            # 如果是已绑定的卡包，添加绑定时间
            if package.is_owned:
                package.bind_time = user_package_map[package.package_id].created_at
                package.user_package_id = user_package_map[package.package_id].package_id
                package.son = user_package_map[package.package_id]
        # 转换时包含is_owned属性
        result = []
        for package in card_packages:
            package_dict = package.to_dict()
            package_dict['is_owned'] = package.is_owned
            if hasattr(package, 'son'):
                package_dict['son'] = package.son.to_dict()
            if hasattr(package, 'user_package_id'):
                package_dict['user_package_id'] = package.user_package_id
            if hasattr(package, 'bind_time'):
                package_dict['bind_time'] = package.bind_time.strftime('%Y-%m-%d')
            result.append(package_dict)
        return {
            'status': 'success',
            'message': '获取成功',
            'data':result
        }, 200